package store

import (
	"errors"
	"hash/crc32"
	"os"
)

const (
	AlignSize = 512
)

var (
	CrcTable          = crc32.MakeTable(crc32.Castagnoli)
	ErrNotFound       = errors.New("store: not found")
	ErrDataCorruption = errors.New("store: data corruption")
	ErrValueTooLarge  = errors.New("store: value too large")
	ErrDuplicatedKey  = errors.New("store: duplicated key")
	ErrEmptyValue     = errors.New("store: empty value")
)

type ReplicaEntry struct {
	Id uint32
	Key uint64
}

func OpenFile(filename, meta string) (*os.File, error) {
	file, err := os.OpenFile(filename, os.O_RDWR, 0666)
	if err != nil {
		return nil, err
	}
	buf := make([]byte, AlignSize)
	_, err = file.Read(buf)
	if err != nil {
		return nil, err
	}
	if len(meta) > AlignSize || string(buf[:len(meta)]) != meta {
		return nil, errors.New("store:can not open file, meta is incorrect.")
	}
	return file, nil
}

func CreateFile(filename, meta string) (*os.File, error) {
	file, err := os.Create(filename)
	if err != nil {
		return nil, err
	}
	buf := make([]byte, AlignSize)
	copy(buf, []byte(meta))
	_, err = file.Write(buf)
	if err != nil {
		return nil, err
	}
	return file, nil
}
